var browserSync = require('browser-sync');
var runSequence = require('run-sequence');
var reload      = browserSync.reload;
var del         = require('del');
var gulp        = require('gulp');
var $           = require('gulp-load-plugins')();
var stylish     = require('jshint-stylish');
var production  = false;
var paths = {
    app: 'app.js',
    server: {
        js: ['./*.js', 'routes/*.js'],
        jade: ['views/*.jade']
    },
    client: {
        main: 'client/**',
        js: ['client/**/*.js', '!client/lib/**/*.js'],
        lib: ['client/lib/**/*.*'],
        image: ['client/**/*.png', 'client/**/*.jpg', 'client/**/*.gif'],
        scss: 'client/**/*.scss',
        jade: 'client/**/*.jade',
        build: 'public/',
    },
    build: {
        main: 'public/',
        css: 'public/',
        js: 'public/',
        lib: 'public/lib/',
        html: 'public/html',
    },
    rev: {
        main: 'rev/',
        json: 'rev/**/*.json',
        js: 'rev/js/',
        image: 'rev/image/',
        css: 'rev/css/',
    },
    bower: {

    },
    livereload: ['public/**', 'views/**']
};



gulp.task('default', function (done) {
    runSequence(
        ['clean-all'],
        ['build'],
        ['serve'],

    done);
});

gulp.task('release', function (done) {
    runSequence(
        ['production', 'clean-all'],
        ['build'],
        ['serve'],
    done);
});

gulp.task('build', function (done) {
    runSequence(
        ['styles'],
        ['scripts', 'images'],
        ['rev-css', 'rev-html'],
    done);
});

gulp.task("production", function(){
    production = true;
});

gulp.task('clean-all', function() {
    del([paths.rev.main, paths.build.main]);
});
gulp.task('clean-rev', function() {
    del([paths.rev.main]);
});
gulp.task('update-css', function (done) {
    runSequence(
        ['styles'],
        ['rev-css'],
    done);
});
gulp.task('styles', function() {
    var AUTOPREFIXER_BROWSERS = [
        'ie >= 10',
        'ie_mob >= 10',
        'ff >= 30',
        'chrome >= 34',
        'safari >= 7',
        'opera >= 23',
        'ios >= 7',
        'android >= 4.4',
        'bb >= 10'
    ];
    return gulp.src(paths.client.scss)
        .pipe($.sourcemaps.init())
        .pipe($.sass({
            precision: 10
        }).on('error', $.sass.logError))
        .pipe($.if(production, $.cssSpriter({
            'spriteSheet': 'client/image/spritesheet.png',
            'pathToSpriteSheetFromCSS': '/image/spritesheet.png'
        })))
        .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
        .pipe($.cleanCss({compatibility: 'ie8'}))
        // .pipe($.concat('main.min.css'))
        .pipe($.size({title: 'CSS', showFiles: true})) 
        
        
        .pipe($.if(!production, gulp.dest(paths.build.css)))
        .pipe($.if(!production, $.sourcemaps.write('')))

        .pipe($.if(production, $.sourcemaps.write('.')))
        .pipe($.if(production, $.rev()))

        .pipe(gulp.dest(paths.rev.main))

        .pipe($.if(production, $.rev.manifest()))
        .pipe($.if(production, gulp.dest(paths.rev.css)))

        .pipe(browserSync.stream());

});

gulp.task('scripts', ['client-scripts', 'lib-scripts']);

gulp.task('server-scripts', ['server-jshint'], function() {
});

gulp.task('client-scripts', ['client-jshint'], function() { 
    return gulp.src(paths.client.js) 
        .pipe($.newer(paths.build.js))
        .pipe($.sourcemaps.init())
        .pipe($.uglify())
        // .pipe($.concat('main.min.js'))
        .pipe($.size({title: 'JS', showFiles: true}))

        .pipe($.if(production, $.rev()))

        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest(paths.build.js))

        .pipe($.if(production, $.rev.manifest()))
        .pipe($.if(production, gulp.dest(paths.rev.js)))

        .pipe(browserSync.stream());
});

gulp.task('server-jshint', function() {
    return gulp.src(paths.server.js)
      .pipe($.jshint())
      .pipe($.jshint.reporter(stylish));
});
gulp.task('lib-scripts',[], function() { 
    return gulp.src(paths.client.lib)  
        .pipe(gulp.dest(paths.build.lib))
});
gulp.task('client-jshint', function() {
    return gulp.src(paths.client.js)
      .pipe($.jshint())
      .pipe($.jshint.reporter(stylish));
});

gulp.task('images', function(){
    return gulp.src(paths.client.image)

        .pipe($.if(production, $.rev()))
        .pipe(gulp.dest(paths.build.main))
          
        .pipe($.if(production, $.rev.manifest()))
        .pipe($.if(production, gulp.dest(paths.rev.image)))
        .pipe($.size({title: 'images', showFiles: true}))
        .pipe(browserSync.stream());
});

gulp.task('rev-css', function () {
    var manifest = gulp.src(paths.rev.json);
    return gulp.src('rev/**/*.css')
        .pipe($.revReplace({
            prefix: '',
            manifest: manifest
        }))
        .pipe($.size({title: 'REVCSS', showFiles: true}))
        .pipe(gulp.dest(paths.build.css));
});

gulp.task('rev-html', function () {
    var manifest = gulp.src(paths.rev.json);
    return gulp.src(paths.client.jade)
        .pipe($.newer(paths.build.main))
        .pipe($.if(production, $.revReplace({
            prefix: '',
            manifest: manifest,
            replaceInExtensions : ['.css', '.jade']
        })))
        .pipe(gulp.dest(paths.build.main))
        // .pipe(browserSync.stream())
        .pipe($.size({title: 'REVHTML', showFiles: true}))
        ;
});
gulp.task('nodemon', function() {
    $.nodemon({
        script: paths.app,
        ignore: [paths.client.main, paths.server.jade, 'node_modules', 'bower_components'],
        ext: 'js'
    }).on('restart', function() {
        setTimeout(reload, 1000);
    });
});
gulp.task('serve', ['nodemon'], function() {
    setTimeout(function(){
        browserSync.init({
            startPath: "/",
            // reloadDelay: 500,
            notify: true,
            logPrefix: 'BrowserSync',
            plugins: [
                {
                    module: "bs-html-injector",
                    options: {
                        files: 'public/html/*.jade'
                    }
                }
            ],
            port : 3003,
            ui: {
                port: 3002,
                weinre: {
                    port: 8080
                }
            },
            proxy: {
                target: "localhost:4000"
            }
        });
    }, 500);
    


    gulp.watch(paths.server.js, ['server-scripts']);
    gulp.watch(paths.client.js, ['client-scripts']); 
    gulp.watch(paths.client.image, ['images']);

    gulp.watch(paths.client.scss, ['update-css']);
    gulp.watch(paths.client.jade, ['rev-html']);
});
